/*===== code build by mstore0.1.3 =====*/

/*===== mstoreDev/editor#showModuleDoc:0 =====*/

$$('showModuleDoc', function(){
    
    var $docDetailPage;
    
    $(function(){
        $docDetailPage = $('#mstoreDocDetailPage');
        $docDetailPage.on('click', '.title li', function(){
            $(this).addClass('current').siblings().removeClass('current');
            var i = $(this).index();
            $docDetailPage.find('.content > div').eq(i).show().siblings().hide();
        });
        $docDetailPage.on('contextmenu', function(e){
            e.preventDefault();
            $(this).hide();
        });
    });
    
    return function(path){
        $util.ajax(function(resp){
            if(resp.err){
                layer.alert(resp.err);
            }else{
                $docDetailPage.html($rtpl(function(){/*
                    <div class="title">
                        <ul>
                            <li class="current">基本信息</li>
                            <li>代码示例</li>
                            <a href="/{{modulePath.replace(/(#.+)/, '.eg.html$1')}}" target="_blank">查看演示</a>
                        </ul>
                    </div>
                    <div class="content">
                        <div class="baseInfo">
                        
                            <h3>模板引用</h3>
                            <div class="info">&lt;!--&amp;{{modulePath}}{{doc.tplargsStr}}--&gt;</div>
                            
                            {{if doc.tplargs.length > 0}}
                            <h3>模板参数</h3>
                            <div class="info paramTable">
                                <table class="mytable">      
                                    <thead><tr><th>字段</th><th>类型</th><th>说明</th><th>默认值</th></tr><thead>
                                    <tbody>
                                    {{each doc.tplargs as item}}
                                    <tr><td>{{item.key}}</td><td>{{item.type}}</td><td>{{item.info}}</td><td>{{item.value}}</td></tr>
                                    {{/each}}
                                    </tobdy>
                                </table>
                            </div>    
                            {{/if}}
                            
                            {{if doc.jsapi.length > 0}}
                            <h3>接口语法</h3>
                            {{each doc.jsapi as item}}
                            <div class="info">{{item.name}}{{if item.argsStr}}({{#item.argsStr.join(', ')}}){{/if}} [{{item.rets.join(', ')}}] {{item.info}}</div>
                            {{/each}}
                            {{/if}}
                            
                            {{if doc.jsargs.length > 0}}
                            <h3>接口参数</h3>
                            <div class="info paramTable">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>字段</th>
                                            <th>类型</th>
                                            <th>说明</th>
                                            <th>默认值</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {{each doc.jsargs as item}}
                                            {{if item == '---'}}
                                                <tr><td>&nbsp;</td><td></td><td></td><td></td></tr>
                                            {{else}}
                                                <tr><td class="keyName">{{item.key}}</td><td>{{item.type}}</td><td>{{item.info}}</td><td>{{item.value}}</td></tr>
                                            {{/if}}
                                        {{/each}}
                                    </tbody>
                                </table>
                            </div>
                            {{/if}}
                            
                            {{if doc.desc}}
                            <h3>模块说明</h3>
                            <p>{{#doc.desc}}</p>
                            {{/if}}
                            
                         </div>
                        <div class="codeDemo" style="display:none">
                            {{if doc.codejs}}
                            <h3>js代码示例</h3>
                            {{#doc.codejs}}
                            {{/if}}
                            
                            {{if doc.codecss}}
                            <h3>css代码示例</h3>
                            {{#doc.codecss}}
                            {{/if}}
                            
                            {{if doc.codehtml}}
                            <h3>html代码示例</h3>
                            {{#doc.codehtml}}
                            {{/if}}
                        </div>                         
                    </div>
                */}, {doc:resp.docData, modulePath:resp.modulePath})).show();
            }
        }, {
            cmd: 'MODULE_GET_DOC_DATA',
            path: path
        });
    };
    
});

/*===== mstoreDev/editor#serchBox:0 =====*/
$$('search', function(){
    
    var searchType;
    var isVisible;
    
    var $searchBox;
    var $searchInput;
    var $searchSuggest;
    var oldValue;
    
    $(window).keyup(function(e){
        if(e.ctrlKey){
            if(e.keyCode == 192){ //~字符
                search('doc');
            }else if(e.keyCode == 32){ //空格
                search('module');
            }
        }
    });
    
    $(window).click(function(e){
        hidePanel(e);
    });
    
    $(function(){
        
        $searchBox = $('#mstoreSearchBox2');
        $searchInput = $searchBox.find('input');
        $searchSuggest = $searchBox.find('.suggest');
        oldValue = '';
        
        $searchInput.keyup(function(e){
            
            var value = $(this).val();
            var $selected = $searchSuggest.find('.selected');
            if(oldValue != value){  //值变则搜索
                querySuggest(oldValue = value);
            }
            
            if(e.keyCode == 13){ //回车
                if($selected[0]){
                    $selected.click();
                }
            }else if(1 || value){
                //38向上，40向下
                if($selected[0]){
                    if(e.keyCode == 38 && $selected.prev()[0]){
                        $selected.prev().addClass('selected');
                        $selected.removeClass('selected');
                    }else if(e.keyCode == 40 && $selected.next()[0]){
                        $selected.next().addClass('selected');
                        $selected.removeClass('selected');
                    }
                }else{
                    $searchSuggest.find('p').eq(0).addClass('selected');
                }
            }else{
                $searchSuggest.hide();
            }
        });
        
        $searchSuggest.on('click', '[mstoreClick=showModuleDoc]', function(){
            hidePanel();
            $$.showModuleDoc($(this).attr('path'));
        });
        
        $searchSuggest.on('click', '[mstoreClick=openEditModuleCode]', function(){
            hidePanel();
            $$.editor.open($(this).attr('path'));
        });
        
    });
    
    search.hide = function(){
        hidePanel();
    };
    
    return search;
    
    function search(type){
        searchType = type;
        showPanel();
    }
    
    function showPanel(){
        if(!isVisible){
            isVisible = true;
            $searchSuggest.hide();
            $searchBox.show();
            $searchInput.val('').focus();
        }
    }
    
    function hidePanel(e){
        if(e && ($(e.target).parents('.mstoreSearchBox')[0] || e.target == $searchBox[0])){
            e.stopPropagation();
        }else{
            if(isVisible){
                isVisible = !true;
                $searchBox.hide();
            }
        } 
    }
    
    function querySuggest(value){
        
        var cmd;
        var mstoreClick;
        if(searchType == 'module'){
            cmd = 'page_modules_get_by_search';
            mstoreClick = 'openEditModuleCode';
        }else if(searchType == 'doc'){
            cmd = 'MODULE_GET_DOCS_BY_SEARCH';
            mstoreClick = 'showModuleDoc';
        }else{
            return;
        }
        
        $util.ajax(function(resp){
            var modules = resp.modules;
            if(modules.length){
                $searchSuggest.html(function(){
                    var ps = [];
                    for(var i = 0; i < modules.length; i++){
                        ps.push('<p mstoreClick="'+ mstoreClick +'" path="'+ modules[i].path +'" >'+ '《' + modules[i].name +'》'+ modules[i].path +'</p>');
                    }
                    return ps.join('');
                }());
            }else{
                $searchSuggest.html('<p style="color:red">找不到模块</p>');
            }
            $searchSuggest.show();
        }, {
            cmd: cmd,
            projectId: $$.page.projectId,
            deps: STORE_DEPS.join(','),
            keyword: value
        });
    }
    
    
});

/*===== mstoreDev/common#aceEditor:0 =====*/
$$('aceEditor', function(){
    
    var editors = {}; //所有编辑器缓存
    var myEditor; //当前的编辑器
    var tabbox; //编辑器选项卡
    var DEFAULT_themeName = $localStorege('DEFAULT_themeName') || 'twilight';
    
    var langTools = ace.require('ace/ext/language_tools');
    var COMPLETE_DATA = [];
    
    langTools.addCompleter({
        getCompletions: function(editor, session, pos, prefix, callback) {
            if (prefix.length === 0) {
                return callback(null, []);
            }else {
                return callback(null, COMPLETE_DATA);
            }
        }
    });
    
    return Ace;
    
    function Ace(index, option){
        option = option || {};
        var aceEditor = ace.edit('codeEditorTextarea'+ index);
        
        aceEditor.setTheme("ace/theme/" + DEFAULT_themeName);
        
        if(option.language){
            aceEditor.session.setMode("ace/mode/"+ option.language);
        }else{
            aceEditor.session.setMode("ace/mode/html");
        }
        
        aceEditor.setFontSize(17);
        aceEditor.setAutoScrollEditorIntoView(true);
        aceEditor.setOption("minLines", 10);
        aceEditor.setOption("maxLines", 28);
        aceEditor.setOption('wrap', 'free');
        aceEditor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        aceEditor.commands.addCommand({
            name: 'copyline',
            bindKey: {win: 'Ctrl-D',  mac: 'Command-D'},
            exec: function(aceEditor) {
                aceEditor.copyLinesDown();
            },
            readOnly: true // 如果不需要使用只读模式，这里设置false
        });
        
        editor.handle = aceEditor;
        editor.reloadComplete = option.reloadComplete ? function(){
            option.reloadComplete(function(data){
                COMPLETE_DATA = data;
            });
        } : function(){};
        editor.setValue = function(value){
            aceEditor.setValue(value);
        };
        editor.focus = function(option){
            aceEditor.scrollToLine(1);
            aceEditor.gotoLine(1);
        };
        
        editor.setTheme = function(themeName){
            aceEditor.setTheme("ace/theme/"+ themeName);
            $localStorege('DEFAULT_themeName', themeName);
        };
        
        return editor;
        
        function editor(){}
        
    }
    
    
    
});    

/*===== mstoreDev/common#editor:0 =====*/
$$('editor', function(){
    
    var pid = 0;
    var editors = {};
    var myEditor;
    var $tabbox;
    var $body;
    var $viewport; //页面视窗
    
    var $projectId;
    var $storeId;
    
    
    $(function(){
        $body = $(document.body);
        $viewport = $('#editorIframe');
        $tabbox = $('#codeEditorTabbox');
        $(document).on('click', '.codeEditorWindow h3 .close', function(){
            editor($(this).parents('.codeEditorWindow').attr('index')).close();
        });
        $tabbox.on('contextmenu', '.item', function(e){
            e.preventDefault();
            editor($(this).attr('index')).close();
        });
        $tabbox.on('click', '.item', function(e){ //激活或者隐藏编辑器
            var thatEditor = editor($(this).attr('index'));
            if(thatEditor != myEditor){
                thatEditor.focus();
            }else{
                thatEditor.hide();
            }
            e.stopPropagation();
        });
        $tabbox.on('click', function(e){
            $(this).toggleClass('hidden');
        });
        $(window).on('resize', function(){
            myEditor && myEditor.autoHeight();
        });
        $(window).on('keydown', function(e){
            if(e.altKey && e.keyCode == 192){ //按下【Alt+`】 键
                if(myEditor){
                    myEditor.view();
                }
            }
        });
    });
    
    editor.open = function(path, option){
        var thatEditor = editors[path];
        if(thatEditor){ //已结存在编辑器
            thatEditor.focus(option); //激活窗口
        }else{
            newEditor(path, option);
        }
    };
    editor.refresh = function(option){
        if($projectId && $storeId && $storeId != option.storeId){ //切换页面编辑的时候，清空原来的编辑器
            $.each(editors, function(path, editor){
                editor.close();
            });
        }
        $projectId = option.projectId;
        $storeId = option.storeId;
    };
    editor.setTheme = function(themeName){
        $.each(editors, function(path, editor){
            editor.ace.setTheme(themeName);
        });
    };
    return editor;
    
    function editor(index){ //获取指定下标的editor对象
        var thatEditor;
        $.each(editors, function(path, editor){
            if(index == editor.index){
                thatEditor = editor;
                return false;
            }
        });
        return thatEditor;
    }
    
    function newEditor(path, option){ //创建仓库编辑器
        option = option || {};
        
        option.reloadComplete = function(setCompleteData){ //编辑器自动提示数据
            $util.ajax(function(resp){
                if(resp.list){
                    setCompleteData(resp.list);
                }
            }, {
                cmd: 'module_get_autocomplete_list', projectId: path.split('/')[0]
            });
        };
        
        var version; //代码版本
        var index = ++pid;
        var myAceEditor;
        var $tabbutton;
        var $container;
        
        if($projectId && $storeId){ //对模块类型进行分组
            var ids = path.split(/[\/#]/);
            
            var moduleType;
            if(ids[0] == $projectId){
                if(ids[1] == $storeId){
                    moduleType = 'privateModule';
                }else{
                    moduleType = 'projectModule';
                }
            }else{
                moduleType = 'globalModule';
            }
            $tabbox.find('.'+ moduleType + 'Box').prepend($tabbutton = $('<div class="item" index="'+ index +'">加载中...</div>'));
            $tabbox.css('margin-top', '-' + $tabbox.height()/2 +'px');
        }else{
            $tabbox
                .append($tabbutton = $('<div class="item" index="'+ index +'">加载中...</div>'))
                .css('margin-top', '-' + $tabbox.height()/2 +'px');
        }
        
        //console.info([$projectId , $storeId])
            
        $body.append($container = 
            $(
                $rtpl(function(){/*
                    <div index="{{index}}" class="codeEditorWindow">
                        <h3><span></span><b class="close">关闭</b></h3>
                        <pre id="codeEditorTextarea{{index}}">数据加载中...</pre>
                    </div>
                */}, {index:index})
            )
        );
        
        var editor = editors[path] = {
            index: index,
            ace: myAceEditor = $$.aceEditor(index, option),
            focus: focus,
            show: show,
            hide: hide,
            close: close,
            autoHeight: autoHeight,
            view: function(){
                saveCodeReady(function(){
                    if($viewport[0]){
                        $viewport[0].contentWindow.location.reload(true);
                        hide();
                    }
                });
            },
            end:null
        };
        
        getCodeReady(function(resp){
            if(resp.err){
                layer.alert(resp.err);
                editor.close();
                return;
            }
            setCommands();
            
            if(option && option.codeReplace){
                resp = option.codeReplace(resp);
            }
            setValue(resp);
            focus(option);
        });
        
        function setCommands(){
            myAceEditor.handle.commands.addCommand({
                name: 'save',
                bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
                exec: function(aceEditor) {
                    saveCodeReady(function(){
                        if($viewport[0]){
                            pageScrolltop = Math.max($viewport[0].contentWindow.document.documentElement.scrollTop, $viewport[0].contentWindow.document.body.scrollTop);
                            $viewport[0].contentWindow.location.reload(true);
                            /*
                            if($viewport[0].attachEvent){
                                $viewport[0].attachEvent("onload", function(){
                                    $($viewport[0].contentWindow).scrollTop(scrolltop);
                                });
                            }else{
                                $viewport[0].onload = function(){
                                    $($viewport[0].contentWindow).scrollTop(scrolltop);
                                };
                            }
                            return;
                            */
                        }
                    });
                },
                readOnly: true // 如果不需要使用只读模式，这里设置false
            });
            myAceEditor.handle.commands.addCommand({
                name: 'hide',
                bindKey: {win: 'Esc',  mac: 'Esc'},
                exec: function() {
                    editor.hide();
                },
                readOnly: true // 如果不需要使用只读模式，这里设置false
            });
        }
        
        function focus(option){
            
            if(myEditor != editor){
                myEditor && myEditor.hide();
            }
            
            editor.show();
            autoHeight();
            
            if(!option){
                return;
            }
            
            option = option || {};
            
            myAceEditor.handle.scrollToLine(1);
            myAceEditor.handle.gotoLine(1);
            myAceEditor.handle.moveCursorTo(10,0);
            
            gotoline(option);
            
        }
        
        function close(){
            $container.remove();
            $tabbutton.remove();
            delete editors[path];
            if(myEditor == editor){
                myEditor = null;
                $('html').removeClass('mstoreOverflowScroll');
            }
        }
        
        function show(){
            myEditor = editor;
            $container.show();
            $tabbutton.addClass('actived');
            $('html').addClass('mstoreOverflowScroll');
            myAceEditor.reloadComplete();
        }
        
        function hide(){
            myEditor = null;
            $container.hide();
            $tabbutton.removeClass('actived');
            $('html').removeClass('mstoreOverflowScroll');
        }
        
        function autoHeight(){
            myAceEditor.handle.setOption(
                "maxLines", 
                Math.max(
                    5, 
                    Math.floor(
                        ($container.height() - $container.find('h3').height()) / $container.find('.ace_text-input').height()
                    )
                )
            );
        }
        
        function gotoline(option){
            var searchText;
            if(option.type == 'ajax'){ //编辑接口
                searchText = RegExp('<script\\s+ajax\\s+'+ option.ajaxid + '(?=\\s+|>)');
            }
            if(option.searchText){
                searchText = option.searchText;
            }
            if(searchText){
                setTimeout(function(){
                    var info = myAceEditor.handle.find(searchText);
                    if(info){
                        myAceEditor.handle.gotoLine(info.start.row + 1);
                    }
                }, 333);
            }
            
            return;
            
            var search_text;
            if(option.bookmark){
                search_text = '<!'+'#'+ option.bookmark +'>';
            }else if (option.ajaxmark){
                search_text = option.ajaxmark;
            }else if(option.text){
                search_text = option.text;
            }
            if(search_text){
                setTimeout(function(){
                    var info = myAceEditor.handle.find(search_text);
                    if(info){
                        myAceEditor.handle.gotoLine(info.start.row + 1);
                    }
                }, 333);
            }
            
        }
        
        function setValue(data){
            version = data.version;
            $container.find('h3 span').html(data.title);
            $tabbutton.html(data.title);
            myAceEditor.setValue(data.code);
        }
        
        function getCodeReady(callback){
            $util.ajax(callback, {
                cmd:'module_get_code', path:path
            });
        }
        
        function saveCodeReady(callback){
            console.info('save.version => '+ version);
            $util.ajax(function(resp){
                if(resp.err){
                    if(resp.err == 'newversion'){
                        if(confirm('发现新版本，请先更新再提交！')){
                            getCodeReady(function(resp){
                                setValue(resp);
                            });
                        }
                    }
                }else{
                    if(version == resp.version){
                        console.info('skip update ');
                    }else{
                        version = resp.version;
                        console.info('update.version => '+ version);
                        callback && callback();
                    }
                }
            }, ({
                cmd:'module_set_code', path:path, code: myAceEditor.handle.getValue(), version: version
            }));
        }
    }
    
}); 

/*===== mstoreDev/editor#page:0 =====*/

var STORE_DATA;
var STORE_DEPS;
$$('page', function(){
    
    var $projectId;
    var $storeId;
    var viewportWindow;
    var viewportDocument;
    var $mstoreModulesPanel;
    
    
    $(function(){
        
        $mstoreModulesPanel = $('#mstoreModulesPanel');
        $mstoreModulesPanel.on('contextmenu', function(e){
            e.preventDefault();
            $(this).toggleClass('hide');
            if($localStorege('mstoreModulesPanel.ishide') == true){
                $localStorege('mstoreModulesPanel.ishide', false);
            }else{
                $localStorege('mstoreModulesPanel.ishide', true);
            }
            resizePanel();
        });
        $mstoreModulesPanel.on('mouseenter', 'li[path]', function(){
            showOverlayer(this, true);
        });
        
        $mstoreModulesPanel.on('mouseleave', 'li[path]', function(){
            hideOverlayer();
        });
        
        if($localStorege('mstoreModulesPanel.ishide') == '1'){
            $mstoreModulesPanel.addClass('hide');
        }
        
        $(window).on('resize', resizePanel);
        resizePanel();
        
    });
    
    page.setStoreId = setStoreId;
    page.reload = function(){
        viewportWindow && viewportWindow.location.reload(true);
    };
    page.refresh = function(option){
        
        STORE_DATA = option.STORE_DATA;
        STORE_DEPS = option.STORE_DEPS;
        viewportWindow = option.window;
        viewportDocument = option.document;
        page.projectId = $projectId = option.projectId;
        page.storeId = $storeId = option.storeId;
        
        $$.editor.refresh({
            projectId: $projectId,
            storeId: $storeId
        });
        
        history.replaceState && history.replaceState(null, document.title = option.document.title, option.window.location.href + (option.window.location.href.indexOf('?') > 0 ? '&' : '?') +'$edit=mstore');
        
        refresh_renderModuleList(option.modules);
        refresh_setErrorModuleClick();
        refresh_setContextmenu();
        
        $(viewportWindow).keyup(function(e){
            if(e.ctrlKey && e.keyCode == 32){ //空格字符
                $$.search('module');
            }
            if(e.ctrlKey && e.keyCode == 192){ //~字符
                $$.search('doc');
            }
        });
        $(viewportWindow).click(function(e){
            $$.search.hide();
        });
        
    };
    
    return page;
    
    function page(option){
        page.projectId = $projectId = option.projectId;
        page.storeId = $storeId = option.storeId;
    }
    
    function setStoreId(newStoreId){
        if(newStoreId == storeId){
            return;
        }
        page.storeId = storeId = newStoreId;
    }
    
    function showOverlayer(theModuleHoverDom, isScroll){
        (function(){
            $('mstoremodule[path="'+ $(this).attr('path') +'"]', viewportDocument).each(function(){
                var width = this.offsetWidth;
                var height = this.offsetHeight;
                var left = $(this).offset().left;
                var top = $(this).offset().top;
                
                var child = $(this).children();
                
                if(child[0]){
                    if(!width){
                        left = child.offset().left;
                        top = child.offset().top;
                    }
                    width = Math.max(width, child[0].offsetWidth);
                    height = Math.max(height, child[0].offsetHeight);
                }
                
                $(viewportDocument.body).append('<div class=mstoreTipsMasklayer style="left:'
                    + left +'px;top:'
                    + top +'px;width:'
                    + width +'px;height:'
                    + height +'px;"></div>');
                
                if(isScroll){
                    //$(viewportWindow).scrollTop(top - 20);
                }
                    
            });
        }).call(theModuleHoverDom);
    }
    
    function hideOverlayer(){
        $('.mstoreTipsMasklayer', viewportDocument).remove();
    }
    
    function refresh_renderModuleList(modules){
        $mstoreModulesPanel.find('ul').html($rtpl(function(){/*
            {{each $data as module}}
                {{if module.type == 'private'}}
                <li class="privateModule" jhand="openEditModuleCode" path="{{module.path}}">《{{module.name}}》{{module.infoPath}}</li>
                {{/if}}
            {{/each}}
            {{each $data as module}}
                {{if module.type == 'project'}}
                <li class="projectModule" jhand="openEditModuleCode" path="{{module.path}}">《{{module.name}}》{{module.infoPath}}</li>
                {{/if}}
            {{/each}}
            {{each $data as module}}
                {{if module.type == 'global'}}
                <li class="globalModule" jhand="openEditModuleCode" path="{{module.path}}">《{{module.name}}》{{module.infoPath}}</li>
                {{/if}}
            {{/each}}
        */}, modules));
        resizePanel();
    }
    
    function refresh_setErrorModuleClick(){
        $(viewportDocument).on('click', '[mstoreClick]', function(e){
            var $button = $(this);
            var fn = ({
                
                openCreateStore: function(){
                    var path = $button.attr('path').split('/');
                    var projectId = path[0];
                    var storeId = path[1];
                    $$.action.openCreateStore(projectId, storeId);
                },
                
                openCreateModule: function(){
                    
                    var path = $button.attr('path');
                    var projectId_storeId = path.split('/');
                    var projectId = projectId_storeId[0];
                    var storeId = projectId_storeId[1].split('#')[0];
                    var moduleId = projectId_storeId[1].split('#')[1];
                    
                    $$.action.openCreateModule(projectId, storeId, moduleId);
                   
                },
                
                openEditModuleCode: function(){
                    $$.editor.open($button.attr('path'), {
                        searchText: $button.attr('errorpath')
                    });
                },
                
                openEditParentModuleCode: function(){
                    $$.editor.open($button.attr('parentPath'), {
                        searchText: $button.attr('path')
                    });
                },
                
                end: null
                
            })[$(this).attr('mstoreClick')];
            fn && fn();
        });
    }
    
    function refresh_setContextmenu(){
        var window = viewportWindow;
        var document = viewportDocument;
        var $targetDom; //当前激活的模块
            
        var $menubox; //右键功能菜单
        var menuleft = 0; //菜单位置
        var menutop = 0;
        
        $(document.body).append($menubox = $('<div id=mstoreContextmenu class="mstoreContextmenu"></div>'));
        
        $(document).on('contextmenu', 'mstoremodule', function(e){
            e.preventDefault();
            e.stopPropagation();
            menuleft = e.pageX;
            menutop = e.pageY;
            showcontextmenu($(this));
        });
        
        $(document).click(function(){
            $menubox.hide();
        });
        
        $menubox.on('click', '[mstoreContextmenuClick]', function(e){
            var button = $(this).attr('mstoreContextmenuClick');
            var path = $(this).attr('path');
            var bookmark = $(this).attr('bookmark');
            e.stopPropagation();
            switch(button){
                case 'showParentModule':
                    menuleft = e.pageX;
                    menutop = e.pageY;
                    showcontextmenu($targetDom.parents('mstoremodule[path="'+ path +'"]'));
                    //showcontextmenu($('mstoremodule[path="'+ path +'"]', document));
                break;
                case 'showChildModuleList':
                    menuleft = e.pageX;
                    menutop = e.pageY;
                    showcontextmenu($targetDom.find('mstoremodule[path="'+ path +'"]'));
                    //showcontextmenu($('mstoremodule[path="'+ path +'"]', document));
                break;
                case 'openEditModuleCode':
                    $$.editor.open(path);
                    $menubox.hide();
                break;
            }
        });
        
        $menubox.on('mouseenter', '[mstoreContextmenuClick]', function(){
            showOverlayer(this, !true);
        });
        $menubox.on('mouseleave', '[mstoreContextmenuClick]', function(){
            hideOverlayer();
        });
        
        function showcontextmenu($this){
            
            if(!$this[0]){
                return layer.alert('当前模块不允许编辑！');
            }
            $targetDom = $this;
            var path = $this.attr('path');
            var parentPath;
            var parent = $this.parents('mstoremodule');
            if(parent[0]){
                parentPath = parent.attr('path');
            }
            
            var childs = [];
            
            $this.find('mstoremodule').each(function(){
                if($(this).parents('mstoremodule')[0] == $this[0]){
                    childs.push(this);
                }
            });
            
            showmenu();
            
            function showmenu(option){

                $menubox
                .html(function(){
                    var html = [];
                    if(parentPath){
                        html.push('<div class="item parent" mstoreContextmenuClick="showParentModule" path="'+ parentPath +'">《'+ parent.attr('name') +'》'+ textpath(parentPath) +'</div>');
                    }
                    
                    html.push('<div class="item current" mstoreContextmenuClick="openEditModuleCode" path="'+path+'">《'+ $this.attr('name') +'》'+ textpath(path) +'</div>');
                    
                    var pathMap = {}; //过滤重复模块
                    $.each(childs, function(i, child){
                        
                        var name = $(child).attr('name');
                        var path = $(child).attr('path');
                        var _projectId = path.split('/')[0];
                        var _storeId = path.split('/')[1].split('#')[0];
                        var className = 'childGlobal';
                        
                        //console.info(path);
                        
                        if(!pathMap[path]){
                            pathMap[path] = true;
                        }else{
                            return;
                        }
                        
                        if(_projectId == $projectId && _storeId == $storeId){
                            className = 'childPrivate';
                        }else if(_projectId == $projectId){
                            className = 'childProject';
                        }
                        
                        html.push('<div class="item '+ className +'" mstoreContextmenuClick="showChildModuleList" path="'+path+'">《'+name+'》'+ textpath(path) +'</div>');
                        
                    });
                    
                    return html.join('');
                }())
                .show();
                
                menuleft += 2;
                if(menuleft + $menubox[0].offsetWidth > $(window).width()){
                    menuleft -= 2;
                    menuleft -= $menubox[0].offsetWidth;
                }

                if(menutop + $menubox[0].offsetHeight > $(window).height() + $(window).scrollTop()){
                    menutop -= $menubox[0].offsetHeight;
                }
                
                $menubox.css({
                    left: menuleft,
                    top: menutop
                });
                
                function textpath(path){
                    var _projectId = path.split('/')[0];
                    var _storeId = path.split('/')[1].split('#')[0];
                    if(_projectId == $projectId && _storeId == $storeId){
                        return path.split('#')[1];
                    }
                    if(_projectId == $projectId){
                        return path.split('/')[1];
                    }
                    return path;
                }
            }
        
        }


    }
    
    var resizePanelTimer;
    function resizePanel(){
        clearTimeout(resizePanelTimer);
        resizePanelTimer = setTimeout(function(){
            if(!$mstoreModulesPanel[0]){
                return;
            }
            if($(window).height() < $mstoreModulesPanel.find('ul')[0].offsetHeight + 30){
                $mstoreModulesPanel.addClass('showScroll').css('height', $(window).height() - 18);
            }else{
                $mstoreModulesPanel.removeClass('showScroll').css('height', 'auto');
            }
        }, 16);
    }
    
});

mstore = $$.page;

/*===== mstoreDev/editor#pageConfig:0 =====*/

$$(function($it){
    
    $it.listen('click', {
        goIndexOrShowStoreList: function(){ //返回首页
            location.href = '/';
        },
        goMyTasksOrShowStoreList: function(){
            location.href = '/mytasks.html';
        },
        goLogin: function(){
              location.href = '/login.html';
        },
        changeStoreEdit: function(e){ //切换编辑页面
            e.stopPropagation();
            //return alert($(this).attr('storeId') + '.html?$edit=mstore');
            location.href = $(this).attr('storeId') + '.html?$edit=mstore';
        },
        openCreateStore: function(){
            $$.action.openCreateStore($projectId());
        },
        openBuildProject: function(){
            open('/' + $projectId() + '.build');
        },
        openProjectDir: function(){
            $$.action.openDir('mstore/'+ $projectId());
        },
        viewSourceCode: function(){
            open($storeId() + '.html?$view=htmlSourceCode');
        },
        refreshPage: function(){
            $$.page.reload(true);
            //viewportWindow && viewportWindow.location.reload(true);
        },
        viewPageDoc: function(){
            open('/' + $projectId() + '.docs?id=' + $storeId());
        },
        toggleVisible: function(){
            $('#mstoreToolbar').toggleClass('hide');
            $('#mstoreViewport').toggleClass('full');
        },
        openEditAjaxCode: function(){
            var path = $(this).attr('path').split(':');
            $$.editor.open(path[0], {
                type: 'ajax', 
                ajaxid: $(this).attr('ajaxid')
            });
        },
        openEditModuleCode: function(){
            $$.editor.open($(this).attr('path'));
        },
        selectEditorTheme: function(){
            $$.editor.setTheme($(this).attr('themeName'));
        },
        logout: function(){
            $it.ajax.logout(function(){
                location.href = '/login.html';
            });
        },
        showUserMenu: function(){
            $('#userMenubox').toggleClass('show');
        },
        searchDoc: function(e){
            e.stopPropagation();
            $$.search('doc');
            
        },
        searchModule: function(e){
            e.stopPropagation();
            $$.search('module');
        }
    });
    
    $it.listen('mouseenter', {
        goMyTasksOrShowStoreList: function(){
            var $button = $(this);
            $it.ajax.getStoreList(function(data){
                $button.find('.menubox').html(
                    $it.tpl.storeList(data)
                );
            });
        },
        goIndexOrShowStoreList: function(){
            var $button = $(this);
            $it.ajax.getStoreList(function(data){
                $button.find('.menubox').html(
                    $it.tpl.storeList(data)
                );
            });
        },
        showAjaxList: function(){
            var $button = $(this);
            $it.ajax.getAjaxList(function(data){
                $button.find('.menubox').html(
                    $it.tpl.ajaxList(data)
                );
            });
        }
    });
    
    $it.extend({
        domready: function(){
            
        } 
    });
    
    
    $it.ajax({
        getStoreList: function(callback){
            $util.ajax(function(resp){
                if(resp.err){
                    layer.alert(resp.err);
                }else{
                    callback({storeList: resp.pageStores});
                }
            }, {
                cmd: 'page_stores_get',
                projectId: $projectId()
            });
        },
        getAjaxList: function(callback){
            $util.ajax(function(resp){
                if(resp.err){
                    layer.alert(resp.err);
                }else{
                    callback({ajaxList:resp.list});
                }
            }, {
                cmd: 'AJAX_GET_LIST',
                path: $projectId() +'/'+ $storeId(),
                projectId: $projectId(),
                storeId: $storeId()
            });
        },
        logout: function(callback){
             $util.ajax(function(resp){
                if(resp.err){
                    layer.alert(resp.err);
                }else{
                    callback();
                }
            }, {
                cmd: 'user_logout'
            });
        }
    });
    
    $it.tpl({
        storeList: function(data){
            return $rtpl(function(){/*
                {{each storeList as store}}
                    <li jhand="changeStoreEdit" storeId="{{store.id}}">《{{store.name}}》{{store.id}}</li>
                {{/each}}
            */}, data);
        },
        ajaxList: function(data){
            return $rtpl(function(){/*
                {{if ajaxList.length == 0}}
                    <li>暂无接口</li>
                {{else}}
                    {{each ajaxList as ajax}}
                        <li jhand="openEditAjaxCode" path="{{ajax.path}}" ajaxid="{{ajax.id}}">《{{ajax.name}}》{{ajax.id}}</li>
                    {{/each}}
                {{/if}}
            */}, data);
        }
        
    });
    
    
    function $projectId(){
        return $$.page.projectId;
    }
    
    function $storeId(){
        return $$.page.storeId;
    }
    
    
});
